<?php
/**
 * Реализация работы feed'ов с mysql
 *
 */
class RssMysql extends RssDbAbsctract
{
	/**
	 * Mysql resource
	 *
	 * @var mysql resource
	 */
	var $link;
	
	function RssMysql()
	{
		$this->RssDbAbsctract();
	}
	
	/**
	 * подключение к серверу mysql
	 *
	 */
	function Connect()
	{
		$this->link=mysql_connect(
			$this->config['host'],
			$this->config['user'],
			$this->config['password']
		);
		mysql_select_db(
			$this->config['database'],
			$this->link
		);
		if ($this->config['codepage'])
		{
			mysql_query("SET CHARACTER SET '".$this->config['codepage']."'",$this->link);
		}
	}
	
	/**
	 * загружаем из базы в объект
	 *
	 * @param RssFeed $object
	 * @param object $search_object
	 */
	function LoadFeed( &$object, $search_object )
	{
		$search_object->need_feed=isset($search_object->need_feed)?$search_object->need_feed:true;
		$search_object->need_atom=isset($search_object->need_atom)?$search_object->need_atom:true;
		
		if ($search_object->need_feed)
		{
			$search_object->feed_url=(isset($search_object->feed_url))?$search_object->feed_url : NULL;
			$search_object->feed_id=(isset($search_object->feed_id))?$search_object->feed_id : NULL;
			$search_object->feed_status=(isset($search_object->feed_status))?$search_object->feed_status : NULL;
			$search_object->feed_where=(isset($search_object->feed_where))?$search_object->feed_where : NULL;
			
			$where_array=array();
			$where='';
			if ($search_object->feed_url)
			{
				$where_array[]="`url`='".$search_object->feed_url."'";
			}
			if ($search_object->feed_status!='any')
			{
				$where_array[]="`status`='".$search_object->feed_status."'";
			}
			
			if (sizeof($where_array)>0)
			{
				$where=" WHERE (".join(") && (",$where_array).")";
			}
			if ($search_object->feed_where)
			{
				$where=$search_object->feed_where;
			}
			
			$s="select * from `{feed}` $where limit 1";
			$q=$this->Query($s);
			if (mysql_num_rows($q))
			{
				$r=mysql_fetch_object($q);
				$object->id				=$r->id;
				$object->url			=$r->url;
				$object->title			=$r->title;
				$object->author			=$r->author;
				$object->update_freq	=$r->update_freq;
				$object->last_update	=$r->last_update;
				$object->default_status	=$r->default_status;
				$object->default_tags	=$r->default_tags;
			}
		}
		
		if ( $search_object->need_atom && ($object->id || $search_object->feed_id) )
		{
			$search_object->feed_id=isset($search_object->feed_id)?$search_object->feed_id:NULL;
			$search_object->atom_url=isset($search_object->atom_url)?$search_object->atom_url:NULL;
			$search_object->atom_order=isset($search_object->atom_order)?$search_object->atom_order : '`date` DESC';
			$search_object->atom_limit=isset($search_object->atom_limit)?'Limit '.$search_object->atom_limit : NULL;
			$search_object->atom_where=(isset($search_object->atom_where))?$search_object->atom_where : NULL;
			/*if ($search_object->feed_url)
			{
				$search_object->feed_id=$object->id;
			}*/
			
			$where_array=array();
			$where='';
			if ($search_object->feed_id)
			{
				$where_array[]="`feed_id`='".$search_object->feed_id."'";
			}
			elseif ( $search_object->feed_url && $object->id)
			{
				$where_array[]="`feed_id`='".$object->id."'";
			}
			
			if ($search_object->atom_url)
			{
				$where_array[]="`url`='".$search_object->url."'";
			}
			
			if ($search_object->atom_url)
			{
				$where_array[]="`url`='".$search_object->url."'";
			}
			
			if (sizeof($where_array)>0)
			{
				$where=" WHERE (".join(") && (",$where_array).")";
			}
			if ($search_object->atom_where)
			{
				$where=$search_object->atom_where;
			}
			
			$s="select * from `{atom}` ".$where." order by ".$search_object->atom_order." ".$search_object->atom_limit;
			$object->data=array();
			$q=$this->Query($s);
			while ($r=mysql_fetch_object($q))
			{
				$atom=new RssAtom();
				$atom->id=$r->id;
				$atom->title=$r->title;
				$atom->body=$r->body;
				$atom->date=strtotime($r->date);
				$atom->edited_date=strtotime($r->edited_date);
				$atom->author=$r->author;
				$atom->url=$r->url;
				if ($search_object->feed_url && $object->id)
				{
					//$atom->feed=&$object;
				}
				else
				{
					//$atom->feed=new RssFeed(&$this);
				}
				$atom->images=unserialize($r->images);
				$object->AddAtom($atom);				
			}
		}
	}
	
	/**
	 * сохраняем feed в базу данных.
	 * В процессе сохранения проверяется "уникальность" feed'ов и записей feed'а
	 *
	 * @param RssFeed $object
	 */
	function SaveFeed( &$object )
	{
		var_export($object);die();
		$s="replace `{feed}`
				SET
			`id`='".$object->id."',
			`url`='".$object->url."',
			`title`='".addslashes($object->title)."',
			`author`='".addslashes($object->author)."',
			`update_freq`='".$object->update_freq."',
			`last_update`='".strftime("%Y-%m-%d %H:%M:%S",$object->last_update)."',
			`default_tags`='".$object->default_tags."',
			`default_status`='".$object->default_status."'";
		$this->Query($s);
		$object->id=mysql_insert_id();
		
		/**
		 * получаем список url
		 */
		$urls=array();
		
		foreach ((array)$object->data as $k=>$v)
		{
			$urls[$v->url]=(object)array(
				'id'=>$v->id,
				'edited_date'=>$v->edited_date
			);
		}
		$s="select * from `{atom}` where `url` in ('".join("','",array_keys($urls))."')";
		$q=$this->Query($s);
		while ($r=mysql_fetch_object($q))
		{
			$urls[$r->url]=(object)array(
				'id'=>$r->id,
				'edited_date'=>$r->edited_date
			);
		}
		
		foreach ((array)$object->data as $k=>$v)
		{
			// станавливаем статус по умолчанию
			if ($object->default_status && !$v->status)
			{
				$v->status=$object->default_status;
				$object->data[$k]->status=$object->default_status;
			}
			if (!$v->edited_date) $v->edited_date=my_time();
			/**
			 * @todo надо поставить тэги по умолчанию
			 */
		
			$s="REPLACE `{atom}` 
				SET 
					`id`='".$v->id."',
					`title`='".addslashes($v->title)."',
					`url`='".$v->url."',
					`date`='".strftime("%Y-%m-%d %H:%M:%S",$v->date)."',
					`edited_date`='".strftime("%Y-%m-%d %H:%M:%S",$v->edited_date)."',
					`body`='".addslashes($v->body)."',
					`feed_id`='".$v->feed->id."',
					`author`='".$v->author."',
					`images`='".serialize($v->images)."',
					`status`='".$v->status."'
					";
			$this->Query($s);
			$object->data[$k]->id=mysql_insert_id($this->link);
		}
	}
	
	/**
	 * выполняется запрос к базе данных
	 *
	 * @param string $s
	 * @return mysql result
	 */
	function Query($s)
	{
		if (!$this->link)
		{
			$this->Connect();
		}
		$s=preg_replace("/`{(.+?)}`/",$this->config['table_prefix']."\\1",$s);
		$q=mysql_query($s,$this->link) or trigger_error(mysql_error()."\n".$s,E_USER_WARNING);
		return $q;
	}
	
	
}
?>